﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MLM.AdminCP.Class;
using MLM.Data;
using System.IO;
using MLM.Base;

namespace MLM.AdminCP.Pages
{
    public partial class BillExportManual : BasePage
    {
        public static MLMDataContext dtct = new MLMDataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                MLMDataContext ct = new MLMDataContext();
                var orderId = long.Parse(Request.QueryString["ID"]);
                var order = ct.Invoices.FirstOrDefault(it => it.InvoiceID == orderId);
                var sellerId = order.DepoID;
                var buyerId = order.UserID;
                var seller = ct.Users.FirstOrDefault(it => it.UserId == sellerId);
                var sellerBank = ct.UserBanks.FirstOrDefault(it => it.UserID == sellerId);
                //HEAD INFO
                HeadFaxTxt.Text = CommonSettingHelper.GetCommonSetting(ct, CommonSettingsContstants.HEAD_FAX);
                HeadEmailTxt.Text = CommonSettingHelper.GetCommonSetting(ct, CommonSettingsContstants.HEAD_EMAIL);
                HeadPhoneTxt.Text = CommonSettingHelper.GetCommonSetting(ct, CommonSettingsContstants.HEAD_PHONE);


                BillNumberLbl.Text = " " + orderId + " / " + DateTime.Parse(order.DateTimeCreated.ToString()).Year;
                SellerAddressLbl.Text = seller.Address;
                BillDateLbl.Text = DateTime.Parse(order.DateTimeCreated.ToString()).ToShortDateString();

                PartnerIdLbl.Text = buyerId + "";
                try
                {
                    SellerNameLbl.Text = seller.FirstName + " " + seller.LastName;
                }
                catch (Exception)
                {
                    SellerNameLbl.Text = "";
                }
                try
                {
                    SellerCityLbl.Text = seller.PostalCode + " " + seller.CityName;
                }
                catch (Exception)
                {
                    SellerCityLbl.Text = "";
                }
                try
                {
                    SellerCountryLbl.Text = ct.Countries.FirstOrDefault(it => it.CountryID == seller.CountryID).Name;
                }
                catch (Exception)
                {
                    SellerCountryLbl.Text = "";
                }
                try
                {
                    SellerPhoneNumberLbl.Text = seller.UserInfos.FirstOrDefault(it => it.UserID == sellerId).HomePhone;
                }
                catch (Exception)
                {
                    SellerPhoneNumberLbl.Text = "";
                }

                //buyer
                var buyer = ct.Users.FirstOrDefault(it => it.UserId == buyerId);
                try
                {
                    BuyerAddressLbl.Text = buyer.Address;
                }
                catch (Exception)
                {
                    BuyerAddressLbl.Text = "";
                }
                try
                {
                    BuyerNameLbl.Text = buyer.FirstName + " " + buyer.LastName;
                }
                catch (Exception)
                {
                    BuyerNameLbl.Text =  "";
                }
                try
                {
                    BuyerCityLbl.Text =  buyer.PostalCode + " " + buyer.CityName;
                }
                catch (Exception)
                {
                    BuyerCityLbl.Text = "";
                }
                try
                {
                    BuyerCountryLbl.Text =
                       ct.Countries.FirstOrDefault(it => it.CountryID == buyer.CountryID).Name;
                }
                catch (Exception)
                {
                    BuyerCountryLbl.Text = "";
                }
                try
                {
                    BuyerPhoneNumberLbl.Text =
                       buyer.UserInfos.FirstOrDefault(it => it.UserID == sellerId).HomePhone;
                }
                catch (Exception)
                {
                   
                }
                //delivery
                var delivery = ct.UserPaymentInfos.FirstOrDefault(it => it.UserID == buyerId);
                try
                {
                    DNameLbl.Text = delivery.FirstName + " " + delivery.LastName;
                    DAddressLbl.Text = delivery.Address ?? "";
                    DCityLbl.Text = delivery.PostalCode + " " + delivery.CityName;
                    DCountryLbl.Text = ct.Countries.FirstOrDefault(it => it.CountryID == delivery.CountryID).Name;
                }
                catch (Exception)
                {
                    DNameLbl.Text = "";
                    DAddressLbl.Text = "";
                    
                }
                //bank
                try
                {
                    AccountNameLbl.Text = sellerBank.AccountName;
                }
                catch (Exception)
                {
                    AccountNameLbl.Text = "";

                }
                try
                {
                    AccountNumberLbl.Text = sellerBank.AccountNumber;
                }
                catch (Exception)
                {
                    AccountNumberLbl.Text = "";
                }
                try
                {
                    BankCodeLbl.Text = sellerBank.BankCode;
                }
                catch (Exception)
                {
                    BankCodeLbl.Text = "";
                }
                try
                {
                    BankNameLbl.Text = sellerBank.BankName;
                }
                catch (Exception)
                {
                    BankNameLbl.Text = "";
                }
                try
                {
                    SWIFTCodeLbl.Text = sellerBank.SWIFTCode;
                }
                catch (Exception)
                {
                    SWIFTCodeLbl.Text = "";
                }
                try
                {
                    BICCodeLbl.Text = sellerBank.BICCode;
                }
                catch (Exception)
                {
                    BICCodeLbl.Text = "";
                }
                try
                {
                    IBANCodeLbl.Text = sellerBank.IBANCode;
                }
                catch (Exception)
                {
                    IBANCodeLbl.Text = "";
                }
                try
                {
                    TaxtIDLbl.Text = seller.TaxID + "";
                }
                catch (Exception)
                {
                    TaxtIDLbl.Text = "";
                }
                //common
                var orderDetails = ct.InvoiceDetails.Where(it => it.InvoiceID == orderId);
                double? tax = 0;
                decimal? priceWithoutTax = 0;
                decimal? priceIncludeTax = 0;
                double? totalPoint = 0;
                foreach (var BillDetail in orderDetails)
                {
                    tax += BillDetail.VAT;
                    totalPoint += BillDetail.Point*BillDetail.Quantity;
                    var price =
                        ct.ProductBases.FirstOrDefault(it => it.ProductBaseID == BillDetail.ProductBaseID).Price;
                    priceWithoutTax +=
                        FormatPrice(price, 0, ct, buyer.RoleID, BillDetail.ProductBaseID, seller.CountryID) * BillDetail.Quantity;
                    priceIncludeTax +=
                        FormatPrice(price, BillDetail.VAT, ct, buyer.RoleID, BillDetail.ProductBaseID, seller.CountryID) * BillDetail.Quantity;// *BillDetail.Quantity + (price * BillDetail.Quantity * BillDetail.VAT / 100);
                }
                if (tax == 0 || tax == null)
                {
                    TaxInEuroLbl.Text = "0%";
                }
                else
                {
                    TaxInEuroLbl.Text = Math.Round(decimal.Parse((tax / orderDetails.Count()).ToString())) + "%";
                }
                TotalAmountOfPointLbl.Text = totalPoint.ToString() + " PV";
                PriceWithoutTaxLbl.Text = NumberUtil.Round(decimal.Parse(priceWithoutTax.ToString())) + " &euro;";
                PriceIncludeTaxLbl.Text = NumberUtil.Round(decimal.Parse((priceIncludeTax ?? 0).ToString())) + " &euro;";
                TaxValueLbl.Text = NumberUtil.Round(decimal.Parse(((priceIncludeTax - priceWithoutTax) ?? 0).ToString())) + " &euro;";

            }
            if (Request.QueryString["t"] != null)
            {
                ExportPdfBtn.Visible = false;
            }
            //export
            if (Request.QueryString["admin"] == null)
            {
                if (Permission.GetCurrentRole() == 1)
                {
                    FooterForAdminPanel.Visible = true;
                    HeaderPanelForAdmin.Visible = true;
                }
                else
                {
                    FooterForAdminPanel.Visible = false;
                    HeaderPanelForAdmin.Visible = false;
                }
            }
            else
            {
                FooterForAdminPanel.Visible = true;
                HeaderPanelForAdmin.Visible = true;
            }
            ExportPdfBtn.Click += new EventHandler(ExportPdfBtn_Click);
        }
        public static int? GetRole(MLMDataContext ct)
        {
            var orderId = long.Parse(HttpContext.Current.Request.QueryString["ID"]);
            var order = ct.Invoices.FirstOrDefault(it => it.InvoiceID == orderId);
            var buyerId = order.UserID;
            var seller = ct.Users.FirstOrDefault(it => it.UserId == buyerId);
            return seller.RoleID;
        }
        public static long? GetCountry(MLMDataContext ct)
        {
            var orderId = long.Parse(HttpContext.Current.Request.QueryString["ID"]);
            var order = ct.Invoices.FirstOrDefault(it => it.InvoiceID == orderId);
            var sellerId = order.DepoID;
            var seller = ct.Users.FirstOrDefault(it => it.UserId == sellerId);
            return seller.CountryID;
        }
        public static string FormatPrice(object price, object tax, MLMDataContext ct, object productid = null, object countryid = null)
        {
            try
            {
                if (productid != null && countryid != null && countryid != "" && productid != "")
                {
                    long Role = Permission.GetCurrentRole();
                    long pId = long.Parse(productid.ToString());
                    long cId = long.Parse(countryid.ToString());
                    var pPrice =
                        ct.ProductPrices.FirstOrDefault(
                            it => it.ProductBaseID == pId && it.CountryID == cId && it.RoleID == Role);
                    if (pPrice != null)
                    {
                        decimal _price = decimal.Parse(pPrice.Price.ToString());
                        decimal _tax = decimal.Parse(tax.ToString());
                        return (NumberUtil.Round(_price + _price * (_tax / 100))).ToString() + " &euro;";
                    }
                    else
                    {
                        decimal _price = decimal.Parse(price.ToString());
                        decimal _tax = decimal.Parse(tax.ToString());
                        return (NumberUtil.Round(_price + _price * (_tax / 100))).ToString() + " &euro;";
                    }
                }
                else
                {
                    decimal _price = decimal.Parse(price.ToString());
                    decimal _tax = decimal.Parse(tax.ToString());
                    return (NumberUtil.Round(_price + _price * (_tax / 100))).ToString() + " &euro;";
                }
            }
            catch (Exception ex)
            {
                return "0";
            }
        }
        void ExportPdfBtn_Click(object sender, EventArgs e)
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            try
            {
                // create an API client instance
                pdfcrowd.Client client = new pdfcrowd.Client("tudeptrai102", "d878e35084066dda27394eaf34b9e050");

                // convert a web page and write the generated PDF to a memory stream                
                ExportPdfBtn.Visible = false;
                MemoryStream Stream = new MemoryStream();
                var url = Request.Url.ToString() + "&t=1";
                if (Permission.GetCurrentRole() == 1)
                {
                    url += "&admin=1";
                }
                client.convertURI(url, Stream);

                // set HTTP response headers
                Response.Clear();
                Response.AddHeader("Content-Type", "application/pdf");
                Response.AddHeader("Cache-Control", "no-cache");
                Response.AddHeader("Accept-Ranges", "none");
                Response.AddHeader("Content-Disposition", "attachment; filename=bill_export.pdf");

                // send the generated PDF
                Stream.WriteTo(Response.OutputStream);
                Stream.Close();
                Response.Flush();
                Response.End();
            }
            catch (pdfcrowd.Error why)
            {
                //Response.Write(why.ToString());
                Email.Send_Email("tu.phunganh@gmail.com", "mlm error", "mlm error: " + why);
            }
        }
        public static decimal FormatPrice(object price, object tax, MLMDataContext ct, int? role, object productid = null, object countryid = null)
        {
            try
            {
                if (productid != null && countryid != null && countryid != "" && productid != "")
                {

                    long pId = long.Parse(productid.ToString());
                    long cId = long.Parse(countryid.ToString());
                    var pPrice =
                        ct.ProductPrices.FirstOrDefault(
                            it => it.ProductBaseID == pId && it.CountryID == cId && it.RoleID == role);
                    if (pPrice != null)
                    {
                        decimal _price = decimal.Parse(pPrice.Price.ToString());
                        decimal _tax = decimal.Parse(tax.ToString());
                        return (_price + _price * (_tax / 100));
                    }
                    else
                    {
                        decimal _price = decimal.Parse(price.ToString());
                        decimal _tax = decimal.Parse(tax.ToString());
                        return _price + _price * (_tax / 100);
                    }
                }
                else
                {
                    decimal _price = decimal.Parse(price.ToString());
                    decimal _tax = decimal.Parse(tax.ToString());
                    return _price + _price * (_tax / 100);
                }
            }
            catch (Exception ex)
            {
                return 0;
            }
        }
        public static string GetVisible()
        {
            try
            {
                var orderId = long.Parse(HttpContext.Current.Request.QueryString["ID"]);
                var order = dtct.Bills.FirstOrDefault(it => it.BillID == orderId);
                var buyerId = order.UserID;
                var buyer = dtct.Users.FirstOrDefault(it => it.UserId == buyerId);
                return (buyer.RoleID == 2 || buyer.RoleID == 3) ? "display:none" : "";
            }
            catch (Exception)
            {
                return "";
            }            
        }
    }
}